package com.lagou.java.sqlSession;

import com.lagou.java.pojo.Configration;
import com.lagou.java.pojo.MapStatement;
import com.lagou.java.pojo.User;
import lombok.*;

import java.lang.reflect.*;
import java.util.List;

@ToString
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class DefaultSqlSession implements SqlSession{

    private Configration configration;

    @Override
    public <E> List<E> selectList(String statementId, Object... args) throws Exception {
        //将要完成对simpleExecutor里面的query方法的调用
        Executor simpleExecutor = new SimpleExecutor();
        MapStatement mapStatement = configration.getStatementMap().get(statementId);
        List<Object> query = simpleExecutor.query(configration, mapStatement, args);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... args) throws Exception {
        List<Object> objects = selectList(statementId, args);
        if(objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或返回结果过多!");
        }
    }

    @Override
    public Integer UpdateOne(String statementId, Object... args) throws Exception {
        Integer result = selectOne(statementId, args);
        return result;
    }


    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk动态代理
        Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层还是执行jdbc代码, 根据不同情况(返回值类型不同), 来调用selectList和selectOne
                //准备参数, 1, stattementId:sql语句的唯一标识;2,namespace.id=接口全限定名.方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = String.format("%s.%s", className, methodName);

                //如果是泛型则返回泛型类型, 如果是普通类型, 则返回对应的类型
                Type genericReturnType = method.getGenericReturnType();

                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                } else if (genericReturnType.getTypeName().equals("int")) {
                    //执行增,删,改操作
                    Integer integer = UpdateOne(statementId, args);
                    return integer;

                }
                return selectOne(statementId, args);
            }
        });
        return (T) o;
    }

    public static void main(String[] args) {
        System.out.println(User.class instanceof Class);
    }

}

